/*
*	Copyright (c) 2009 Brent Mombourquette
*
*	Permission is hereby granted, free of charge, to any person
*	obtaining a copy of this software and associated documentation
*	files (the "Software"), to deal in the Software without
*	restriction, including without limitation the rights to use,
*	copy, modify, merge, publish, distribute, sublicense, and/or sell
*	copies of the Software, and to permit persons to whom the
*	Software is furnished to do so, subject to the following
*	conditions:
*
*	The above copyright notice and this permission notice shall be
*	included in all copies or substantial portions of the Software.
*
*	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
*	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
*	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*	OTHER DEALINGS IN THE SOFTWARE.
*
*	This file contains functions that do not involve the extracting of information to be logged.
*/
// Import a referrence to the BreadCrumbs database
Components.utils.import("resource://BreadCrumbs/database.jsm");

var realTimeUpdate; 	// A callback function between util.js and graph_page.html to update the graph in real time
var realTimeReload;		// A callback function between util.js and graph_page.html to update the graph when starting a new session
var realTimeTitleChange; // A callback bunction between util.js and graph_page.html to update the tooltip of a node that has had its title altered via the Quick Title Edit button

var util = {
	/*
	 * Register the callback function for having the graph update in real time.
	 * @param {Function} func
	 */
	registerUpdateCallback: function(func){
		realTimeUpdate = func;
	},
	
	/*
	 * Register the callback for reloading the graph when a new session is started or loaded.
	 * @param {Function} func
	 */
	registerReloadCallback: function(func){
		realTimeReload = func;
	},
	
	/*
	 * Register the callback for updating a nodes tooltip when a new title is entered via the Quick Title Edit button.
	 * @param {Function} func
	 */
	registerQuickCallback: function(func){
		realTimeTitleChange = func;
	},

	/*
	 * Toggle the logging feature on and off.
	 * Globals: destURL [from log.js], on [from log.js], turnedOn [from log_helper.js]
	 */
	toggleLogging: function() {
		var pic = document.getElementById("breadcrumbs-statusicon");
		if (!on) {
			on = true;
			turnedOn = true;
			pic.setAttribute('src','chrome://BreadCrumbs/content/on.png');
			pic.setAttribute('tooltiptext', 'Click to pause Logging');
			destURL = content.document.URL;
			logData.log(content.document, content.window); //Always log the first site once turned on.
		} else {
			on = false;
			pic.setAttribute('src','chrome://BreadCrumbs/content/off.png');
			pic.setAttribute('tooltiptext', 'Click to continue Logging');
		}
	},
	
	/*
	 * Open the window to edit the title for the current URL.
	 * Globals: on [from log.js]
	 */
	quickTitleEdit: function() {
		if (on) {
			var getEntryString = "SELECT row,destination,title FROM edgeLog WHERE destination=?1;";
			var getEntryStatement = breadcrumbsDBConn.createStatement(getEntryString);
			getEntryStatement.bindUTF8StringParameter(0, content.document.URL);
			// The row, destination, and title need to be extracted to pass to the annotation window
			var r, d, t;
			try {
				while(getEntryStatement.executeStep()){
					if (r || d || t) { // We want to extract the FIRST database entry where destionation = content.document.URL
						continue;
					} else {
						r = getEntryStatement.getInt32(0);
						d = getEntryStatement.getUTF8String(1);
						t = getEntryStatement.getUTF8String(2);
					}
				}
			} finally {
				getEntryStatement.reset();
				getEntryStatement.finalize();
			}
			
			var quickWindow = window.openDialog("chrome://BreadCrumbs/content/annotate_node.xul", "Title", "chrome,centerscreen", {oldTitle: t, url: d, row: r} );
			// Set up a timer to continuously check until the annotation window has been closed
			var quickTimer = setTimeout(function() { util.watchQuickForClose(quickWindow, quickTimer, r)}, 1000);
		} else { //Logging isnt on so this site may not have an entry in the database, just prevent from editing unless it has ben logged
			var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
			prompts.alert(null, "Cannot Edit Title", "The logging feature must be turned on to use Quick Title Edit. This will edit the title of the current website, if it has been logged by BreadCrumbs.");
		}
	},
	
	/*
	 * Once win is closed, update the node's tooltip on the graph in graph_page.html (if this page is open). This function is called on a timer.
	 * Globals: realTimeTitleChange()
	 * @param {Window} win
	 * @param {Timer} quickTimer
	 * @param {Integer} row			The row number in the database that this node/title corresponds to
	 */
	watchQuickForClose: function( win, quickTimer, row ) {
		if (!win || win.closed) { 
			try {
				realTimeTitleChange(row); // Update the title in the graph
			} catch(e) {} // This means that graph_page.html is not open
			clearTimeout(quickTimer); //Stop the timer
		} else { // Continue the timer
			quickTimer = setTimeout(function(){util.watchQuickForClose(win, quickTimer, row)},1000);
		}
	},
	
	/*
	 * Set the appropriate variables to facilitate a smooth transition upon loading a past session.
	 * Globals: destURL, first, sorURL	[all from log.js]
	 * @param {String} source
	 * @param {String} destination
	 */
	resetAfterLoad: function(source, destination) {
		var win = window.top.getBrowser().selectedBrowser.contentWindow;
		destURL = destination;	
		// Start the user at where they left off in the session that has been loaded
		win.open(destURL);
		// Sets sorURL to the source address of where they left off, so everything is exactly the same. 
		// Note that destination and source are the last entry of the database
		sorURL = source;	
		first = false;
	},
	
	/*
	* Delete the contents of the database.
	*/
	deleteAll: function() {		
		var deleteDatabaseString = "DELETE FROM edgeLog;";
		var deleteDatabaseStatement = breadcrumbsDBConn.createStatement(deleteDatabaseString);
		
		try {
			while(deleteDatabaseStatement.executeStep()){
			}
		} finally {
			deleteDatabaseStatement.reset();
			deleteDatabaseStatement.finalize();
		}
	},
	
	/*
	 * Visit the Understanding BreadCrumbs wiki page of the BreadCrumbs google code page: http://code.google.com/p/breadcrumbsplugin/
	 */
	viewHelp: function() {
		window.getBrowser().selectedTab = window.getBrowser().addTab("http://code.google.com/p/breadcrumbsplugin/wiki/Understanding");
	}
}